// pagesA/makeorder/makeorder.js

const app = getApp()
import http from "../../utils/http"
import util from "../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    current: 0,
    iswx: 1,
    goods_id: '',
    goods_sku_id: '',
    num: '',
    skill_id: '',
    sku: '',
    price: '',
    money: '',
    discount: '',
    timeInfo: '',
    coupon: '',
    to_shop: 1,
    paytype: 0,
    address: '',
    sumprice: '',
    traveltype: 0,
    memo: '',
    choose_skill_type: '',
    travel: '',
    totalMoney: '',
    info: '',
    shop: '',
    userInfo: '',
    show: false,
    day: 0,
    now: new Date().getTime(),
    dayTime: [],
    year: '',
    list: [],
    shop_id: '',
    safeBottom: `30px`,
    today: 0,
    skillInfo: '',
    giveMoney: '',
    seckill_id: '', // 秒杀id

    showDate: false,
    moreDate: '',
    minDate: new Date(2024, 6, 1).getTime(),
  },

  onDisplayDate() {
    this.setData({ 
      showDate: true,
      minDate: new Date().getTime() + 60 * 60 * 24 * 3 * 1000,
    });
  },
  onCloseDate() {
    this.setData({ showDate: false });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  onConfirmDate(event) {
    const index = 3;
    const start = event.detail;
    this.setData({
      showDate: false,
      moreDate: this.formatDate(start),
      timeInfo: {
        starttime: new Date(start).getTime(),
      },
      [`dayTime[${index}]`]: { day: '更多', time: util.formatTime(new Date(start).getTime(), 'mm-dd') },
    });
// 啊啊啊的阿斯顿
    this.setData({
      day: index
    })
    this.setData({
      list: []
    })
    this.getTime()
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  getTotal() {
    let travelMoney = 0,
      couponMoney = 0;
    if (this.data.travel) {
      travelMoney = Number(this.data.travel.distance_price)
    }
    if (this.data.coupon) {
      couponMoney = this.data.coupon.reduce
    }
    this.setData({
      totalMoney: ((this.data.price * this.data.num) * this.data.userInfo.discount / 100 - couponMoney + travelMoney).toFixed(2)
    })
    if (this.data.totalMoney == 0) {
      this.setData({
        paytype: 4
      })
    }
  },
  level() {
    util.skip('/service/level/level', {
      'changePlus': (data) => {
        this.getInfo()
      }
    })
  },
  couponTap() {
    util.skip('/service/mycoup/mycoup?goods_id=' + this.data.goods_id + '&money=' + this.data.price * this.data.num + '&shop_id=' + this.data.shop_id, {
      'selectCoupon': (data) => {
        this.setData({
          coupon: data.info
        })
        this.getTotal()
      }
    })
  },
  repay() {
    if (this.data.current == 0 && !this.data.address) {
      util.toast('请添加地址')
      return
    }
    wx.requestSubscribeMessage({
      tmplIds: [app.globalData.templateconfig.user_notice_template, app.globalData.templateconfig.user_order_template, app.globalData.templateconfig.order_finish_template],
      success: (res) => {
        console.log(res)
      },
      fail: (e) => {
        console.log(e)
      },
      complete: (res) => {
        this.pay()
      }
    })

  },
  pay() {
    let data = {
      goods_id: this.data.goods_id,
      goods_sku_id: this.data.goods_sku_id,
      traveltype: this.data.traveltype,
      choose_skill_type: this.data.info.choose_skill_type,
      to_shop: this.data.current == 1 ? 'shop' : 'door',
      address_id: this.data.address ? this.data.address.id : '',
      coupon_id: this.data.coupon ? this.data.coupon.id : '',
      skill_id: this.data.current == 1 ? '' : this.data.skill_id,
      seckill_id: this.data.seckill_id ? this.data.seckill_id : '',
      shop_id: this.data.shop_id,
      paytype: this.data.paytype,
      time_id: this.data.skill_id ? this.data.timeInfo.id : '',
      num: this.data.num,
      memo: this.data.memo,
      travel_price: this.data.travel ? this.data.travel.distance_price : 0,
      distance: this.data.travel ? this.data.travel.distance : 0,
      starttime: this.data.timeInfo.starttime,
      city: this.data.current == 1 ? this.data.shop.city : this.data.address.city
    }

    http.post('order/createorder', data, true).then(res => {
      if (this.data.paytype == 4) {
        wx.redirectTo({
          url: '/service/result/result?type=1&order_id='+res.data.order_id
        })
      } else {
        wx.requestPayment({
          timeStamp: res.data.pay.timeStamp,
          nonceStr: res.data.pay.nonceStr,
          package: res.data.pay.package,
          signType: res.data.pay.signType,
          paySign: res.data.pay.paySign,
          success: (result) => {
            wx.redirectTo({
              url: '/service/result/result?type=1&order_id='+res.data.order_id
            })
          },
          fail: (res) => {
            wx.redirectTo({
              url: '/service/myorder/myorder?type=1&active=1'
            })
          }
        })
      }
    })
  },
  setMemo(e) {
    this.setData({
      memo: e.detail.value
    })
  },
  numChange(e) {
    this.setData({
      num: e.detail
    })
    this.getTotal()
  },
  changepay(e) {
    this.setData({
      paytype: e.currentTarget.dataset.index
    })
  },
  change(e) {
    if (e.currentTarget.dataset.index == 1 && this.data.to_shop === 1) {
      return
    } else if (e.currentTarget.dataset.index == 0 && this.data.to_shop === 2) {
      return
    }
    this.setData({
      current: Number(e.currentTarget.dataset.index)
    })
    this.getTravel()

  },
  //跳转地址管理
  toaddress() {
    util.skip('/service/addressmanager/addressmanager?type=1', {
      selectAddress: (data) => {
        this.setData({
          address: data
        })
        this.getTravel()
      }
    })
  },
  change1() {
    this.setData({
      myclass: 'item ',
      myclass1: 'item active',
      current: 1
    })
  },
  choose(e) {
    let time = e.currentTarget.dataset.info
    this.setData({
      timeInfo: {
        starttime: time.starttime,
        id: time.id
      }
    })
    this.getTravel()
  },
  chooseTime() {
    this.setData({
      show: true
    })
  },
  chooseTravel(e) {
    this.setData({
      traveltype: Number(e.currentTarget.dataset.type)
    })
    this.getTravel()
  },
  changeDay(e) {
    const index = 3;
    this.setData({
      [`dayTime[${index}]`]: { day: '更多', time: ''},
      moreDate: '',
      day: Number(e.currentTarget.dataset.index)
    })
    this.setData({
      list: []
    })
    this.getTime()
  },
  getTime() {
    if (this.data.skill_id) {
      http.get('skill/skilltime', {
        timetype: this.data.day,
        skill_id: this.data.skill_id
      }).then(res => {
        this.setData({
          list: res.data
        })
      })
    } else {
      let day = this.data.year + '-' + this.data.dayTime[this.data.day].time + ' 00:00:00'
      let start = new Date(day).getTime() / 1000
      let end = start + 24 * 60 * 60 - 1
      for (let i = start; i < end; i += 1800) {
        this.data.list.push({
          starttime: i,
          state: 0,
          id: i
        })
      }
      this.setData({
        list: this.data.list
      })
    }

  },
  getInfo() {
    let data = {
      goods_id: this.data.goods_id,
      goods_sku_id: this.data.goods_sku_id,
      num: this.data.num
    }
    if (this.data.skill_id) {
      data['skill_id'] = this.data.skill_id
    }
    if (this.data.seckill_id) {
      data['seckill_id'] = this.data.seckill_id
    }
    http.get('order/settle', data).then(res => {
      let timeInfo;
      if (this.data.skill_id) {
        timeInfo = res.data.timeInfo
        this.setData({
          now: (new Date().getTime() + 30 * 60 * 1000) / 1000
        })
      } else {
        let time = new Date().getTime() + res.data.settle.goods.response_hour * 60 * 60 * 1000 - 1 * 60 * 1000;
        let date = new Date(time);
        let d = date.getDate();
        let h = date.getHours();
        let m = date.getMinutes();
        date.setSeconds(0)
        if (m <= 30) {
          date.setMinutes(30)
        } else if (m > 30) {
          date.setMinutes(0)
          date.setHours(h + 1)

        }
        if (date.getHours() >= res.data.settle.goods.end_hour) {
          date.setDate(d + 1)
          date.setHours(res.data.settle.goods.start_hour)
          date.setMinutes(0)
          this.setData({
            day: 1,
            today: 1
          })
        } else if (date.getHours() < res.data.settle.goods.start_hour) {
          date.setHours(res.data.settle.goods.start_hour)
          date.setMinutes(0)
        }

        this.setData({
          now: Date.parse(date) / 1000
        })
        timeInfo = {
          starttime: Date.parse(date) / 1000,
          id: ''
        }
      }
      this.setData({
        skillInfo: res.data.skillInfo,
        info: res.data.settle.goods,
        shop: res.data.settle.shop,
        traveltype: res.data.settle.goods.is_travel,
        sku: res.data.settle.goodsSku,
        price: res.data.settle.goods.price,
        money: res.data.money,
        userInfo: res.data.userInfo,
        discount: res.data.userInfo.discount,
        timeInfo: timeInfo,
        choose_skill_type: res.data.settle.goods.choose_skill_type
      })
      if (this.data.info.to_shop.split(',').indexOf('door') !== -1 && this.data.info.to_shop.split(',').indexOf('shop') !== -1) {
        this.setData({
          to_shop: 3,
          current: 0
        })
      } else if (this.data.info.to_shop.split(',').indexOf('door') !== -1) {
        this.setData({
          to_shop: 1,
          current: 0
        })
      } else if (this.data.info.to_shop.split(',').indexOf('shop') !== -1) {
        this.setData({
          to_shop: 2,
          current: 1
        })
      }
      this.getTotal()
      this.getTime()
      if (this.data.to_shop === 1 || this.data.to_shop === 3) {
        http.get('address/addresslist', {
          page: 1,
        }).then(res => {
          this.setData({
            address: res.data[0]
          })
          this.getTravel()
        })
      }
    })
  },
  getTravel() {
    if (this.data.address && this.data.choose_skill_type === 1 && this.data.skill_id && this.data.current === 0) {
      if (this.data.info.is_travel == 1) {
        http.get('order/travelprice', {
          goods_id: this.data.goods_id,
          time_id: this.data.timeInfo.id,
          city: this.data.address.city,
          address_id: this.data.address.id,
          skill_id: this.data.skill_id,
          traveltype: this.data.traveltype
        }).then(res => {

          this.setData({
            travel: res.data
          })
          this.getTotal()
        }).catch(err => {
          this.setData({
            traveltype: 1
          })
        })
      }

    } else {
      this.setData({
        travel: ''
      })
      this.getTotal()
    }
  },
  // 获取赠送金额
  getGiveMoney(){
    http.get('order/settle', {
      goods_id: 38,
      goods_sku_id: '',
      num: 1
    }).then(res => {
      this.setData({
        giveMoney: res.data.give_money
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let now = new Date().getTime();
    const high = app.globalData.safeBottom
    this.setData({
      safeBottom: `${high}px`
    })
    this.setData({
      goods_id: options.goods_id,
      goods_sku_id: options.goods_sku_id,
      num: options.num,
      skill_id: options.skill_id || '',
      seckill_id: options.seckill_id || '',
      shop_id: options.shop_id || '',
      dayTime: [
        { day: '今天', time: util.formatTime(now, 'mm-dd') },
        { day: '明天', time: util.formatTime(now + 86400000, 'mm-dd') },
        { day: '后天', time: util.formatTime(now + 172800000, 'mm-dd') },
        { day: '更多', time: ''},
      ],
      year: util.formatTime(now, 'yyyy')
    })
    this.getInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getGiveMoney();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})